package fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.hardware.SensorManager;
import android.location.Location;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.example.menhoo.toollibrary.android.log.Log;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.assist.Network;
import com.example.menhoo.toollibrary.common.helper.AndroidFileUtil;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.helper.PhoneUtil;
import com.example.menhoo.toollibrary.common.utils.AndroidUtil;
import com.example.menhoo.toollibrary.common.utils.BitmapUtil;
import com.example.menhoo.toollibrary.common.utils.FileUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.example.menhoo.toollibrary.common.utils.LocationUtils;
import com.example.menhoo.toollibrary.common.utils.ShakeUtil;
import com.example.menhoo.toollibrary.common.utils.StringUtil;
import com.example.menhoo.toollibrary.common.utils.VibrateUtil;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.util.LogUtils;
import com.socks.library.KLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.map.BasicMapActivity;
import app.Main;
import app.PreviewFileInfo;
import app.ScaleDocImage;
import app.ScaleImage;
import application.AppApplication;
import application.HttpUrlConstant;
import application.UIApplication;
import interfaces.IDownLoadListener;
import interfaces.IFileChooserListener;
import interfaces.IReturnObject;
import interfaces.IUpLoadListener;
import mainUI.AppFragment;
import menhoo.com.i8officelibrary.R;
import model.DownloadDbModel;
import model.FileInfo;
import model.ImageInfo;
import model.UploadImage;
import receiver.NetStateReceiver;
import service.DownLoadService;
import tools.WeiXinTool;

/**
 * setJavaScriptEnabled(true);  //支持js
 * <p>
 * setPluginsEnabled(true);  //支持插件
 * <p>
 * setUseWideViewPort(false);  //将图片调整到适合webview的大小
 * <p>
 * setSupportZoom(true);  //支持缩放
 * <p>
 * setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局
 * <p>
 * supportMultipleWindows();  //多窗口
 * <p>
 * setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //关闭webview中缓存
 * <p>
 * setAllowFileAccess(true);  //设置可以访问文件
 * <p>
 * setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
 * <p>
 * webview webSettings.setBuiltInZoomControls(true); //设置支持缩放
 * <p>
 * setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
 * <p>
 * setLoadWithOverviewMode(true); // 缩放至屏幕的大小
 * <p>
 * setLoadsImagesAutomatically(true);  //支持自动加载图片
 * Created by yanglei on 15/9/17.
 */
public class WebHtml extends AppFragment {

    private static final String TAG = "WebHtml";

    //url约定
    public static final String _uniqueUrl = "http://www.menhoo.i8jsfunction.com";
    /**
     * http请求之后多长时间超时
     */
    private int Http_Timeout = UIApplication.NetWorkTimeOut;

    private Handler mHandler = new Handler();
    private IReturnObject shakeJsFunction;
    private PhoneObject phoneObject = new PhoneObject();
    private String Url;

    boolean webViewIsOk = true;
    /**
     * 当前容器是否是主菜单页面
     */
    private boolean IsMainPage = false;
    private ShakeUtil shakeUtil;
    private SensorManager sensorManager; //定义sensor管理器, 注册监听器用

    //支持html input file
    public ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> mUploadMessageForAndroid5;
    public final static int FILECHOOSER_RESULTCODE = 101;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 201;

    public WebView webView;//这个必须自己来实例化因为如果不是webView= new WebView(getActivity());这种形式，在Fragment中用webview，当html页面中有select标签的时候webview会报错，原因是找不到能当dialog弹出框的载体activity

    LinearLayout webViewLinearLayout;
    private ProgressDialog progressBar;

    @Override
    public boolean onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            getActivity().finish();
        }
        return true;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContextView(R.layout.fragment_web_html);

        try {
            Url = getArguments().getString("Url");
            KLog.e("url==="+ Url);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

        try {
            IsMainPage = getArguments().getBoolean("IsMainPage");
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }


    }

    //超时run
    Runnable runTimeOut = new Runnable() {
        @Override
        public void run() {
            if (webView.getProgress() < 100) {
                LogUtils.e("链接超时");
                showError();
            }
        }
    };

    @Override
    public void init() {
        super.init();
        //
        try {
            webViewLinearLayout = (LinearLayout) rootView.findViewById(R.id.webViewLinearLayout);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

        webView = new WebView(getActivity());
        webViewLinearLayout.addView(webView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        //先显示,等页面都加载完成再决定,到底显不显示
        setTitleDisplay(true);
        if (!IsMainPage) {
            setBtnBackDisplay(true);
        }

        shakeUtil = new ShakeUtil(context) {
            @Override
            public void onShake() {

                if (shakeJsFunction != null) {
                    long[] vibrateLong = {0, 500};
                    VibrateUtil.vibrate(context, vibrateLong, -1);
                    shakeJsFunction.returnResult(null);
                }
            }
        };
        //

        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Reload();
                return false;
            }
        });
        webView.requestFocusFromTouch();
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);//设置此属性，可任意比例缩放
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);//设置支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setDisplayZoomControls(false);//setDisplayZoomControls是在Android 3.0中新增的API.
        webSettings.setAllowFileAccess(true);  //设置可以访问文件
        webSettings.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true);  //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8"); //默认编码
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//设置页面缓存 LOAD_NO_CACHE 不缓存只从网络获取
//        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //html5 本地存储
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getAppActivity().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

        webView.setWebContentsDebuggingEnabled(true);
        //html页面可以调用的js对象名称
        webView.addJavascriptInterface(phoneObject, "phoneObject");

        //如果页面中链接，如果希望点击链接继续在当前browser中响应，而不是新开Android的系统browser中响应该链接，必须覆盖 webview的WebViewClient对象
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!UrlLoad(view, url)) {
                    //view.loadUrl(url);
                    loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // super.onPageStarted(view, url, favicon);
                KLog.e("webview:onPageStarted:" + url);

                //2018.5.26加入进度条
                if (progressBar == null) {
                    progressBar = ProgressDialog.show(getContext(), null, "页面加载中，请稍后..");
                }
                //超时
//                HandlerUtil.runOnUiThreadDelay(runTimeOut, Http_Timeout);

            }

            //网页载入完成的时候
            public void onPageFinished(WebView view, String url) {

                //2018.5.26加入进度条
                if (progressBar != null) {
                    progressBar.dismiss();
                    progressBar = null;
                }

                if (webViewIsOk) {
                    webView.requestFocus();
                    super.onPageFinished(view, url);
                    hideAll(1000);
                    if (IsMainPage && getActivity() instanceof Main) {
//                        ((Main) getActivity()).getTabTipNum();
                    }
                }

            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                //super.onReceivedError(view, request, error);
                showError();
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                //super.onReceivedHttpError(view, request, errorResponse);
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                } else {
                    showError();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                //super.onReceivedError(view, errorCode, description, failingUrl);
                showError();

            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                //super.onReceivedSslError(view, handler, error);
                handler.proceed();

            }


        });
        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                //载入进度
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                showSimpleDialogMessage(message, false);
                result.confirm();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult jsResult) {
                showSimpleDialogMessage(message, new IReturnObject() {
                    @Override
                    public void returnResult(Object result) {
                        jsResult.confirm();
                    }
                }, new IReturnObject() {
                    @Override
                    public void returnResult(Object result) {
                        jsResult.cancel();
                    }
                }, false, true);

                return true;
            }


            //扩展浏览器上传文件
            //3.0++版本
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooserImpl(uploadMsg);
            }

            //3.0--版本
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooserImpl(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooserImpl(uploadMsg);
            }

            // For Android > 5.0
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> uploadMsg, WebChromeClient.FileChooserParams
                    fileChooserParams) {
                openFileChooserImplForAndroid5(uploadMsg);
                return true;
            }


        });

        if (!Check.isEmpty(Url)) {
            loadUrl(Url);
        }
    }

    public void loadUrl(final String urlPar) {

        webViewIsOk = true;

        showLoading();
        Map<String, String> parm1 = HttpUrlConstant.getUrlParameters(urlPar);

        Map<String, String> parm = new HashMap();
        if (parm1==null||!parm1.containsKey("__session__"))
            parm.put("__session__", AppApplication.getSession());
        parm.put("openType", "i8app");
        if (IsMainPage) {
            parm.put("isMainPage", "true");
        }
        final String url_ = HttpUrlConstant.getWebSiteFullUrl(urlPar, parm);
        KLog.e(urlPar+"===webView--loadUrl===" + url_);
        //检查一下网络状态

        boolean isNetwork = Network.isConnected(context);
        if (isNetwork) {
            Intent it = new Intent();// 创建Intent对象
            it.setAction(NetStateReceiver.Action);
            it.putExtra("isNetworkAvailable", true);
            it.putExtra("message", getString(com.example.menhoo.menhoolibrary.R.string.available_network_title));
            context.sendBroadcast(it);

            //2018-5-16加入cookie
            syncCookie(url_);

            webView.loadUrl(url_);
            LogUtils.i("WebHtml url:" + url_);
        } else {
            showError();
        }

    }


    /**
     * 2018-5-16 登录用户访问网页需要加入cookie
     *
     * @param url
     */
    private void syncCookie(String url) {
        try {
            CookieSyncManager.createInstance(getContext());//创建一个cookie管理器
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除以前的cookie
            cookieManager.removeAllCookie();
            StringBuilder sbCookie = new StringBuilder();//创建一个拼接cookie的容器,为什么这么拼接，大家查阅一下http头Cookie的结构
            sbCookie.append("APPKIZTICKET=" + AppApplication.getSession());//拼接sessionId
            String cookieValue = sbCookie.toString();
//            Log.i(TAG, cookieValue);
            cookieManager.setCookie(url, cookieValue);//为url设置cookie
            CookieSyncManager.getInstance().sync();//同步cookie
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showError() {
        webViewIsOk = false;
        webView.stopLoading();
        webView.loadData("", "text/html", "UTF-8");
        showError(new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                loadUrl();
            }
        });
        String message = getString(com.example.menhoo.menhoolibrary.R.string.no_conn_server);

        Intent it = new Intent();// 创建Intent对象
        it.setAction(NetStateReceiver.Action);
        it.putExtra("isNetworkAvailable", false);
        it.putExtra("message", message);
        context.sendBroadcast(it);
    }


    public void loadUrl() {
        loadUrl(Url);
    }

    public void Reload() {
        showSimpleDialogMessage("是否重新载入当前页面？", new IReturnObject() {
            @Override
            public void returnResult(Object result) {
                HandlerUtil.runOnUiThreadDelay(new Runnable() {
                    @Override
                    public void run() {
                        loadUrl();
                    }
                }, 400);

            }
        }, true, true);
    }

    /**
     * 返回true 则截断原始url的跳转,false继续按原始的url跳转
     *
     * @param view
     * @param url
     * @return 返回true 则截断原始url的跳转,false继续按原始的url跳转
     */
    public boolean UrlLoad(WebView view, final String url) {
        if (url.toLowerCase().indexOf(_uniqueUrl.toLowerCase()) >= 0) {
            Map<String, String> urlParameters = HttpUrlConstant.getUrlParameters(url);

            if (urlParameters == null || !urlParameters.containsKey("json")) {
                return false;
            }

            try {
                final String jsonStr = URLDecoder.decode(URLDecoder.decode(urlParameters.get("json").toString(), "UTF-8"), "UTF-8");//URLDecoder.decode(urlParameters.get("json").toString(), "UTF-8");

                mHandler.post(new Runnable() {

                    @Override
                    public void run() {

                        try {
                            //小震一下
//                            VibrateUtil.vibrateShot(getActivity());
                            LogUtils.d(url);
                            //
                            final JSONObject jsonObj = new JSONObject(jsonStr);
                            String action = jsonObj.getString("action");

                            //解析一下新的模塊參數

                            String url = null;
                            String tag = null;

                            DownLoadService downLoadService = null;
                            Intent it = null;
                            switch (action) {
                                //添加摇一摇
                                case "addShakeHandler":
                                    shakeJsFunction = new IReturnObject() {
                                        @Override
                                        public void returnResult(Object result) {
                                            executeJavascript("_shakeJsFunction()");
                                        }
                                    };
                                    break;
                                //移除摇一摇
                                case "removeShakeHandler":
                                    shakeJsFunction = null;
                                    break;
                                //上传文件
                                case "uploadFile":
                                    final String uploadTag = jsonObj.getString("tag");
                                    final String uploadUrl = jsonObj.getString("uploadUrl");

                                    getAppActivity().openFileChooser(new IFileChooserListener() {
                                        @Override
                                        public void FileChooser(Context context, Intent intent, String fileFullName) {
                                            if (Check.isEmpty(fileFullName)) {
                                                return;
                                            }

                                            DownLoadService downLoadService = getAppActivity().getDownLoadService();
                                            if (downLoadService != null) {

                                                getAppActivity().setUploadLoadReceiverHandle(new IUpLoadListener() {
                                                    @Override
                                                    public void UploadStart(Context context, Intent intent, String url, String
                                                            tag) {
                                                        executeJavascript("_uploadStartFunction(url,tag)".replace("url", "'" +
                                                                url + "'").replace("tag", "'" + tag + "'"));
                                                    }

                                                    @Override
                                                    public void UploadLoading(Context context, Intent intent, String url, long
                                                            total, long current, String tag) {
                                                        executeJavascript("_uploadLoadingFunction(url, total, current,tag)"
                                                                .replace("url", "'" + url + "'").replace("total", "" + total)
                                                                .replace
                                                                        ("current", "" + current).replace("tag", "'" + tag +
                                                                        "'"));
                                                    }

                                                    @Override
                                                    public void UploadFinish(Context context, Intent intent, String url, String
                                                            filePath, String webResult, String tag) {
                                                        executeJavascript("_uploadFinishFunction(url,filePath,webResult,tag)"
                                                                .replace("url", "'" + url + "'").replace("filePath", "'" +
                                                                        filePath + "'").replace
                                                                        ("webResult", "'" + webResult + "'").replace("tag", "'"
                                                                        + tag +
                                                                        "'"));
                                                    }

                                                    @Override
                                                    public void UploadCancelled(Context context, Intent intent, String url,
                                                                                String tag) {
                                                        executeJavascript("_uploadCancelledFunction(url,tag)".replace("url", "'" +
                                                                url + "'").replace("tag", "'" + tag + "'"));
                                                    }

                                                    @Override
                                                    public void UploadError(Context context, Intent intent, String url, String
                                                            errorMsg, String tag) {
                                                        executeJavascript("_uploadErrorFunction(url,errorMsg,tag)".replace
                                                                ("url", "'" + url + "'").replace("errorMsg", "'" + errorMsg +
                                                                "'").replace("tag", "'" + tag + "'"));
                                                    }

                                                });

                                                downLoadService.upload(uploadTag,
                                                        uploadUrl,
                                                        fileFullName);
                                            }
                                        }
                                    });
                                    break;
                                //上传多张照片
                                case "uploadImageMulti":
                                    final String uploadTagMulti = jsonObj.getString("tag");
                                    final String uploadUrlMulti = jsonObj.getString("uploadUrl");
                                    final String selectImageCount = jsonObj.getString("selectImageCount");
                                    int selectImageCount_int = 9;
                                    try {
                                        selectImageCount_int = Integer.parseInt(selectImageCount);
                                    } catch (Exception e) {
                                    }
                                    if (selectImageCount_int > 1) {
                                        getAppActivity().openImageFileChooserMulti(true, selectImageCount_int, new
                                                IFileChooserListener() {
                                                    @Override
                                                    public void FileChooser(Context context, Intent intent, String fileFullName) {

                                                        if (Check.isEmpty(fileFullName)) {
                                                            return;
                                                        }
                                                        DownLoadService downLoadService = getAppActivity().getDownLoadService();
                                                        if (downLoadService != null) {

                                                            getAppActivity().setUploadLoadReceiverHandle(new IUpLoadListener() {
                                                                @Override
                                                                public void UploadStart(Context context, Intent intent, String url, String
                                                                        tag) {
                                                                    executeJavascript("_uploadStartFunction(url,tag)".replace("url", "'" +
                                                                            url + "'").replace("tag", "'" + tag + "'"));
                                                                }

                                                                @Override
                                                                public void UploadLoading(Context context, Intent intent, String url, long
                                                                        total, long current, String tag) {
                                                                    executeJavascript("_uploadLoadingFunction(url, total, current,tag)"
                                                                            .replace("url", "'" + url + "'").replace("total", "" + total)
                                                                            .replace
                                                                                    ("current", "" + current).replace("tag", "'" + tag +
                                                                                    "'"));
                                                                }

                                                                @Override
                                                                public void UploadFinish(Context context, Intent intent, String url, String
                                                                        filePath, String webResult, String tag) {
                                                                    executeJavascript("_uploadFinishFunction(url,filePath,webResult,tag)"
                                                                            .replace("url", "'" + url + "'").replace("filePath", "'" +
                                                                                    filePath + "'").replace
                                                                                    ("webResult", "'" + webResult + "'").replace("tag", "'"
                                                                                    + tag +
                                                                                    "'"));
                                                                }

                                                                @Override
                                                                public void UploadCancelled(Context context, Intent intent, String url,
                                                                                            String tag) {
                                                                    executeJavascript("_uploadCancelledFunction(url,tag)".replace("url", "'" +
                                                                            url + "'").replace("tag", "'" + tag + "'"));
                                                                }

                                                                @Override
                                                                public void UploadError(Context context, Intent intent, String url, String
                                                                        errorMsg, String tag) {
                                                                    executeJavascript("_uploadErrorFunction(url,errorMsg,tag)".replace
                                                                            ("url", "'" + url + "'").replace("errorMsg", "'" + errorMsg +
                                                                            "'").replace("tag", "'" + tag + "'"));
                                                                }

                                                            });

                                                            String[] fileFullNameArry = fileFullName.split(",");
                                                            for (String fullName : fileFullNameArry) {
                                                                File ff = new File(fullName);

                                                                downLoadService.upload(uploadTagMulti + "_" + ff.getName(),
                                                                        uploadUrlMulti,
                                                                        fullName);
                                                            }

                                                        }
                                                    }
                                                });
                                    } else {
                                        getAppActivity().openImageFileChooserSingle(true, new
                                                IFileChooserListener() {
                                                    @Override
                                                    public void FileChooser(Context context, Intent intent, String fileFullName) {

                                                        if (Check.isEmpty(fileFullName)) {
                                                            return;
                                                        }
                                                        DownLoadService downLoadService = getAppActivity().getDownLoadService();
                                                        if (downLoadService != null) {

                                                            getAppActivity().setUploadLoadReceiverHandle(new IUpLoadListener() {
                                                                @Override
                                                                public void UploadStart(Context context, Intent intent, String
                                                                        url, String
                                                                                                tag) {
                                                                    executeJavascript("_uploadStartFunction(url,tag)".replace
                                                                            ("url", "'" +
                                                                                    url + "'").replace("tag", "'" + tag + "'"));
                                                                }

                                                                @Override
                                                                public void UploadLoading(Context context, Intent intent,
                                                                                          String url, long
                                                                                                  total, long current, String tag) {
                                                                    executeJavascript(("_uploadLoadingFunction(url, total, " +
                                                                            "current,tag)")
                                                                            .replace("url", "'" + url + "'").replace("total",
                                                                                    "" + total)
                                                                            .replace
                                                                                    ("current", "" + current).replace("tag",
                                                                                    "'" + tag +
                                                                                            "'"));
                                                                }

                                                                @Override
                                                                public void UploadFinish(Context context, Intent intent, String
                                                                        url, String
                                                                                                 filePath, String webResult, String tag) {
                                                                    executeJavascript(("_uploadFinishFunction(url,filePath," +
                                                                            "webResult,tag)")
                                                                            .replace("url", "'" + url + "'").replace
                                                                                    ("filePath", "'" +
                                                                                            filePath + "'").replace
                                                                                    ("webResult", "'" + webResult + "'")
                                                                            .replace("tag", "'"
                                                                                    + tag +
                                                                                    "'"));
                                                                }

                                                                @Override
                                                                public void UploadCancelled(Context context, Intent intent,
                                                                                            String url,
                                                                                            String tag) {
                                                                    executeJavascript("_uploadCancelledFunction(url,tag)"
                                                                            .replace("url", "'" +
                                                                                    url + "'").replace("tag", "'" + tag + "'"));
                                                                }

                                                                @Override
                                                                public void UploadError(Context context, Intent intent, String
                                                                        url, String
                                                                                                errorMsg, String tag) {
                                                                    executeJavascript("_uploadErrorFunction(url,errorMsg,tag)"
                                                                            .replace
                                                                                    ("url", "'" + url + "'").replace("errorMsg", "'" +
                                                                                    errorMsg +
                                                                                    "'").replace("tag", "'" + tag + "'"));
                                                                }

                                                            });

                                                            String[] fileFullNameArry = fileFullName.split(",");
                                                            for (String fullName : fileFullNameArry) {
                                                                File ff = new File(fullName);

                                                                downLoadService.upload(uploadTagMulti + "_" + ff.getName(),
                                                                        uploadUrlMulti,
                                                                        fullName);
                                                            }

                                                        }
                                                    }
                                                });
                                    }

                                    break;
                                case "downloadFile":
                                    final String downloadTag = jsonObj.getString("tag");
                                    final String downloadUrl = jsonObj.getString("downloadUrl");

                                    getAppActivity().setDownLoadReceiverHandle(new IDownLoadListener() {
                                        @Override
                                        public void DownloadStart(Context context, Intent intent, String url, String tag) {
                                            executeJavascript("_downloadStartFunction(url,tag)".replace("url", "'" + url + "'")
                                                    .replace("tag", "'" + tag + "'"));
                                        }

                                        @Override
                                        public void DownloadLoading(Context context, Intent intent, String url, long total,
                                                                    long current, String tag) {
                                            LogUtils.e("下载提示: current=" + current + ";total=" + total + "; url:" + url);
                                            executeJavascript("_downloadLoadingFunction(url, total, current,tag)".replace
                                                    ("url", "'"
                                                            + url + "'").replace("total", "" + total).replace
                                                    ("current", "" + current).replace("tag", "'" + tag + "'"));
                                        }

                                        @Override
                                        public void DownloadFinish(Context context, Intent intent, String url, String filePath,
                                                                   String tag) {
                                            executeJavascript("_downloadFinishFunction(url,filePath,tag)".replace("url", "'" +
                                                    url + "'").replace("filePath", "'" + filePath + "'").replace("tag", "'" +
                                                    tag + "'"));
                                        }

                                        @Override
                                        public void DownloadCancelled(Context context, Intent intent, String url, String tag) {
                                            executeJavascript("_downloadCancelledFunction(url,tag)".replace("url", "'" + url +
                                                    "'").replace("tag", "'" + tag + "'"));
                                        }

                                        @Override
                                        public void DownloadError(Context context, Intent intent, String url, String errorMsg,
                                                                  String tag) {
                                            executeJavascript("_downloadErrorFunction(url,errorMsg,tag)".replace("url", "'" +
                                                    url + "'").replace("errorMsg", "'" + errorMsg + "'").replace("tag", "'" +
                                                    tag + "'"));
                                        }

                                    });

                                    downLoadService = getAppActivity().getDownLoadService();
                                    if (downLoadService != null) {
                                        downLoadService.addDownloadQueue(downloadTag, downloadUrl, AppApplication
                                                .getAppDownLoadPath(context, downloadUrl));
                                    }
                                    break;
                                case "callPhoneHandler":
                                    String phoneNumber = jsonObj.getString("phoneNumber");
                                    PhoneUtil.callPhone(context, phoneNumber);
                                    break;
                                case "sendSmsHandler":
                                    String phoneNumber2 = jsonObj.getString("phoneNumber");
                                    String message = jsonObj.getString("message");
                                    PhoneUtil.callSMS(context, phoneNumber2, message);
                                    break;
                                case "sendEmailHandler":
                                    String emailAddress = jsonObj.getString("emailAddress");
                                    String subject = jsonObj.getString("subject");
                                    String text = jsonObj.getString("text");
                                    PhoneUtil.callEmail(context, emailAddress, subject, text);
                                    break;
                                case "downloadCancelled":
                                    url = jsonObj.getString("url");
                                    downLoadService = getAppActivity().getDownLoadService();
                                    if (downLoadService != null) {
                                        downLoadService.cancelDownload(url);
                                    }
                                    break;
                                case "getDownloadFileList":
                                    List<DownloadDbModel> list = AppApplication.getDownloadFiles();

                                    if (list != null && list.size() > 0) {
                                        JSONArray jsonListArray = new JSONArray();
                                        for (DownloadDbModel list_item : list) {
                                            jsonListArray.put(list_item.getJsonObject());
                                        }
                                        executeJavascript("_getDownloadFileList(result)".replace("result", "'" + jsonListArray
                                                .toString() + "'"));
                                    } else {
                                        executeJavascript("_getDownloadFileList(null)");
                                    }

                                    break;
                                case "getDownloadFile":
                                    tag = jsonObj.getString("tag");
                                    DownloadDbModel downloadDbModel = AppApplication.getDownloadFileForTag(tag);
                                    if (downloadDbModel == null) {
                                        executeJavascript("_getDownloadFile(null)");
                                    } else {
                                        executeJavascript("_getDownloadFile(result)".replace("result", "'" + downloadDbModel
                                                .getJsonObject().toString() + "'"));
                                    }

                                    break;
                                case "showFile":
                                    JSONObject fileInfo = jsonObj.isNull("fileInfo") ? null : jsonObj.getJSONObject("fileInfo");
                                    JSONObject imgInfo = jsonObj.isNull("imgInfo") ? null : jsonObj.getJSONObject("imgInfo");
                                    boolean defaultFileInfoView = jsonObj.isNull("defaultInfoView") ? false : jsonObj.getBoolean("defaultInfoView");

                                    String showFile_fileName = null, showFile_fileSize = null, showFile_fileDate = null, showFile_downloadUrl = null, showFile_downloadTag = null, showFile_thumbUrl = null;
                                    JSONObject showFile_metadata = null;
                                    if (fileInfo != null) {
                                        showFile_fileName = fileInfo.isNull("fileName") ? null : fileInfo.getString("fileName");
                                        showFile_fileSize = fileInfo.isNull("fileSize") ? null : fileInfo.getString("fileSize");
                                        showFile_fileDate = fileInfo.isNull("fileDate") ? null : fileInfo.getString("fileDate");
                                        showFile_downloadUrl = fileInfo.isNull("downloadUrl") ? null : fileInfo.getString("downloadUrl");
                                        showFile_downloadTag = fileInfo.isNull("downloadTag") ? fileInfo.getString("fileName") : fileInfo.getString("downloadTag");
                                        showFile_thumbUrl = fileInfo.isNull("thumbUrl") ? null : fileInfo.getString("thumbUrl");
                                        showFile_metadata = fileInfo.isNull("metadata") ? null : fileInfo.getJSONObject("metadata");
                                    }
                                    JSONArray showFileUrlArray = null;
                                    String imageInfoTitle = null;
                                    int curIndex = 1;
                                    if (imgInfo != null) {
                                        imageInfoTitle = imgInfo.isNull("title") ? null : imgInfo.getString("title");
                                        showFileUrlArray = imgInfo.isNull("urls") ? null : imgInfo.getJSONArray("urls");
                                        curIndex = imgInfo.isNull("curIndex") ? 1 : imgInfo.getInt("curIndex");

                                    }
                                    String[] showFile_Urls = null;
                                    if (showFileUrlArray != null) {
                                        showFile_Urls = new String[showFileUrlArray.length()];
                                        for (int i = 0; i < showFileUrlArray.length(); i++) {
                                            showFile_Urls[i] = showFileUrlArray.getString(i);
                                        }
                                    }
                                    HashMap<String, String> metadataMap = null;
                                    if (showFile_metadata != null && showFile_metadata.names().length() > 0) {
                                        JSONArray showFile_metadata_names = showFile_metadata.names();
                                        metadataMap = new HashMap<String, String>();
                                        for (int i = 0; i < showFile_metadata_names.length(); i++) {
                                            metadataMap.put(showFile_metadata_names.getString(i), showFile_metadata.getString(showFile_metadata_names.getString(i)));
                                        }
                                    }

                                    //
                                    FileInfo showFile_FileInfo = null;
                                    if (fileInfo != null) {
                                        showFile_FileInfo = new FileInfo();
                                        showFile_FileInfo.fileName = showFile_fileName;
                                        showFile_FileInfo.fileSize = showFile_fileSize;
                                        showFile_FileInfo.fileDate = showFile_fileDate;
                                        showFile_FileInfo.downloadUrl = HttpUrlConstant.getWebSiteFullUrl(showFile_downloadUrl);
                                        showFile_FileInfo.downloadTag = showFile_downloadTag;
                                        showFile_FileInfo.thumbUrl = checkURL(showFile_thumbUrl);
                                        showFile_FileInfo.metadata = metadataMap;
                                    }


                                    ImageInfo showFile_ImageInfo = new ImageInfo();
                                    showFile_ImageInfo.title = imageInfoTitle;
                                    showFile_ImageInfo.urls = showFile_Urls;
                                    showFile_ImageInfo.curIndex = curIndex;
                                    //
                                    if (defaultFileInfoView) {
                                        it = new Intent(getAppActivity(), PreviewFileInfo.class);// 创建Intent对象
                                    } else {
                                        if (showFile_ImageInfo.urls != null && showFile_ImageInfo.urls.length == 1) {
                                            it = new Intent(getAppActivity(), ScaleImage.class);// 创建Intent对象
                                        } else if (showFile_ImageInfo.title.endsWith(".ppt") || showFile_ImageInfo.title.endsWith(".pptx")) {
                                            it = new Intent(getAppActivity(), ScaleImage.class);// 创建Intent对象
                                        } else if (showFile_ImageInfo.title.endsWith(".doc") || showFile_ImageInfo.title.endsWith(".docx")) {
                                            it = new Intent(getAppActivity(), ScaleDocImage.class);// 创建Intent对象
                                        } else {
                                            it = new Intent(getAppActivity(), ScaleImage.class);// 创建Intent对象
                                        }
                                    }
                                    //imgInfo
                                    it.putExtra("imageInfo", showFile_ImageInfo);
                                    //fileInfo
                                    it.putExtra("fileInfo", showFile_FileInfo);

                                    startActivity(it);
                                    getActivity().overridePendingTransition(com.example.menhoo.menhoolibrary.R.anim.anim_scale_in, com.example.menhoo
                                            .menhoolibrary.R
                                            .anim.anim_scale_out);

                                    break;
                                case "closePage":
                                    String  module = jsonObj.getString( "app");//日曆模塊直接關閉
                                    if(module.equals("calendar") ){
                                        getActivity().finish();
                                    }else{
                                        getActivity().onBackPressed();
                                    }
                                    break;
                                case "openFile":
                                    String openFilePath = jsonObj.getString("filePath");
                                    if (!Check.isEmpty(openFilePath) && new File(openFilePath).exists()) {
                                        startActivity(AndroidFileUtil.openFile(openFilePath));
                                    } else {
                                        MessageUtil.showShortToast(context, "文件不存在:" + openFilePath);
                                    }
                                    break;
                                case "showToast":
                                    String showToastMessage = jsonObj.getString("message");
                                    MessageUtil.showShortToast(context, showToastMessage);
                                    break;
                                case "showDialog":
                                    String showDialogMessage = jsonObj.getString("message");
                                    showSimpleDialogMessage(showDialogMessage, new IReturnObject() {
                                        @Override
                                        public void returnResult(Object result) {
                                            executeJavascript("_showMessageFunction()");
                                        }
                                    }, true, true);
                                    break;
                                case "sessionOverdue":
                                    getAppActivity().sessionOverdue();
                                    break;
                                case "applicationTitleBarDisplay":
                                    boolean isShowTitleBar = jsonObj.getBoolean("isShowTitleBar");
                                    setTitleDisplay(isShowTitleBar);
                                    if (IsMainPage) {
                                        setBtnBackDisplay(false);
                                    } else {
                                        setBtnBackDisplay(true);
                                    }
                                    break;
                                case "applicationTipShow":
                                    String tipMessage = jsonObj.getString("message");
                                    if (IsMainPage) {
                                        try {
                                            ((Main) getActivity()).showTip(getTitle(), tipMessage);
                                        } catch (Exception e) {
                                            LogUtils.e("" + e.getMessage());
                                        }
                                    } else {
                                        //应该在AutoFragment的右上角来提示,但是现在还没有想好是否这么做
                                    }
                                    break;
                                case "applicationTipHide":
                                    if (IsMainPage) {
                                        try {
                                            ((Main) getActivity()).hideTip(getTitle());
                                        } catch (Exception e) {
                                            LogUtils.e("" + e.getMessage());
                                        }
                                    } else {

                                    }
                                    break;
                                case "getGps":
                                    try {
                                        final LocationUtils.OnLocationChangeListener mOnLocationChangeListener = new LocationUtils.OnLocationChangeListener() {

                                            @Override
                                            public void getLastKnownLocation(Location location) {
                                                final String latitude = String.valueOf(location.getLatitude());
                                                final String longitude = String.valueOf(location.getLongitude());
                                            }

                                            @Override
                                            public void onLocationChanged(Location location) {
                                                //location = LocationUtils.Mars2Baidu(location);
                                                final String latitude = String.valueOf(location.getLatitude());
                                                final String longitude = String.valueOf(location.getLongitude());

                                                HandlerUtil.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        executeJavascript("_gpsJsFunction(x,y)".replace("x", "'" + longitude +
                                                                "'").replace("y", "'" + latitude + "'"));
                                                    }
                                                });


                                                LocationUtils.unregister();
                                            }

                                            @Override
                                            public void onStatusChanged(String provider, int status, Bundle extras) {

                                            }
                                        };
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Looper.prepare();
                                                boolean isSuccess = LocationUtils.register(context, 0, 0, mOnLocationChangeListener);
                                                if (!isSuccess) {
                                                    HandlerUtil.runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            executeJavascript("_gpsJsFunction(x,y)".replace("x", "'" + "null" +
                                                                    "'").replace("y", "'" + "null" + "'"));
                                                        }
                                                    });
                                                }
                                                Looper.loop();
                                            }
                                        }).start();
                                    } catch (Exception e) {
                                    }

                                    break;
                                case "weixinShareText":
                                    try {
                                        String weixinText = jsonObj.getString("text");
                                        WeiXinTool.text(weixinText);

                                    } catch (Exception e) {
                                    }

                                    break;
                                case "weixinShareURL":
                                    try {
                                        final String weixinTitle = jsonObj.getString("title");
                                        final String weixinUrl = jsonObj.getString("urlString");
                                        final String weixinDesc = jsonObj.getString("description");
                                        String weixinImgUrl = jsonObj.getString("thumbImgUrl");

                                        if (StringUtil.isEmpty(weixinImgUrl)) {
                                            Bitmap thumb = BitmapUtil.getRoundedCornerBitmap(BitmapFactory.decodeStream(context.getResources()
                                                    .openRawResource(R.raw.app_icon_title)), 15f);
                                            WeiXinTool.html(weixinTitle, thumb, weixinUrl, weixinDesc);
                                        } else {
                                            getBitmapLoader().display(null, weixinImgUrl, new BitmapLoadCallBack<View>() {
                                                @Override
                                                public void onLoadCompleted(View container, String uri, Bitmap bitmap, BitmapDisplayConfig config, BitmapLoadFrom from) {
                                                    WeiXinTool.html(weixinTitle, bitmap, weixinUrl, weixinDesc);
                                                }

                                                @Override
                                                public void onLoadFailed(View container, String uri, Drawable drawable) {

                                                }
                                            });
                                        }


                                    } catch (Exception e) {
                                    }

                                    break;
                                case "bcw_upload":

                                    final String uploadUrlImage = jsonObj.getString("uploadUrl");
                                    final JSONObject uploadImageFormat = jsonObj.getJSONObject("uploadImageFormat");
                                    final long size = uploadImageFormat.getLong("size");
                                    final String shapeWidth = uploadImageFormat.getString("shapeWidth");
                                    final String shapeHeight = uploadImageFormat.getString("shapeHeight");
                                    final String thumbWidth = uploadImageFormat.getString("thumbWidth");
                                    final String thumbHeight = uploadImageFormat.getString("thumbHeight");
                                    final String uploadTagImage = jsonObj.getString("tag");
                                    final String params = jsonObj.getString("params");

                                    final int tw = Integer.valueOf(thumbWidth).intValue();
                                    final int th = Integer.valueOf(thumbHeight).intValue();
                                    final int sw = Integer.valueOf(shapeWidth).intValue();
                                    final int sh = Integer.valueOf(shapeHeight).intValue();


                                    getAppActivity().openImageFileChooserMulti(true, 9, new
                                            IFileChooserListener() {
                                                @Override
                                                public void FileChooser(Context context, Intent intent, String fileFullName) {

                                                    if (Check.isEmpty(fileFullName)) {
                                                        return;
                                                    }
                                                    String driverid = AndroidUtil.getUniqueID(getActivity());
                                                    JSONObject json = new JSONObject();
                                                    JSONArray images = new JSONArray();
                                                    try {
                                                        json.put("tag", jsonObj.getString("tag"));
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }

                                                    String[] fileFullNameArry = fileFullName.split(",");
                                                    for (String fullName : fileFullNameArry) {
                                                        File ff = new File(fullName);

                                                        String filename = driverid + "" + (new Date()).getTime();
                                                        JSONObject jsonimage = new JSONObject();
                                                        String base64 = BitmapUtil.imgToBase64(ff.getAbsolutePath(), tw, th);
                                                        try {

                                                            long fileSize = 0;
                                                            if (ff.exists()) {
                                                                fileSize = ff.length();
                                                            }

                                                            jsonimage.put("id", filename);
                                                            jsonimage.put("total", fileSize);
                                                            jsonimage.put("base64String", base64);
                                                            images.put(jsonimage);

                                                            UploadImage m = new UploadImage();
                                                            m.imageID = filename;
                                                            m.total = fileSize;
                                                            m.filePath = ff.getAbsolutePath();
                                                            m.TAG = jsonObj.getString("tag");
                                                            m.params = jsonObj.getString("params");
                                                            upLoadList.add(m);
                                                        } catch (JSONException e) {
                                                            e.printStackTrace();
                                                            LogUtils.e(e.toString());
                                                        }
                                                        LogUtils.e(filename);


                                                    }
                                                    try {
                                                        json.put("images", images);
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                    executeJavascript("receiveDataFuntion('filesThumb', tag)"
                                                            .replace("tag", "'" + json.toString() + "'"));
                                                    startUpLoadImage(checkURL(uploadUrlImage), sw, sh, size, 0);

                                                }
                                            });
                                    break;
                                //取消上传
                                case "bcw_cancel":
                                    String s = jsonObj.toString();
                                    final String imageCancelid = jsonObj.getString("id");
                                    final String imageCancelTAG = jsonObj.getString("tag");
                                    if (nowUpLoad.imageID.equals(imageCancelid)) {
                                        nowHandler.cancel();
                                    }
                                    if (upLoadList.size() > 0) {
                                        for (int i = upLoadList.size(); i > 0; i--) {
                                            if (upLoadList.get(i - 1).imageID.equalsIgnoreCase(imageCancelid)) {
                                                String deleFP = upLoadList.get(i - 1).filePath;
                                                upLoadList.remove(i - 1);
                                                try {
                                                    FileUtil.deleteFile(new File(deleFP));
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                case "getMapLocationHandler":
                                    it = new Intent(getActivity(), BasicMapActivity.class);
                                    it.putExtra("title", jsonObj.getString("displayText"));
                                    startActivityForResult(it, ADDRES_GET);
                                    break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            LogUtils.e(e.getMessage() + "");
                        }

                    }
                });


            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            return true;
        }

        return false;
    }

    /**
     * 传入 js脚本 如executeJavascript("alert('hahaha')")   这个是无返回值的js方法
     */
    public void executeJavascript(String JavascriptStr) {
        webView.loadUrl("javascript:" + JavascriptStr + ";");
    }

    /**
     * 传入 js脚本 如executeJavascript("alert('hahaha')")   这个是有返回值的js方法
     */
    public void executeJavascript(String JavascriptStr, IReturnObject<String> onFinction) {
        phoneObject.setOnFinction(onFinction);
        webView.loadUrl("javascript:window.phoneObject.getResultContext(" + JavascriptStr + ");");
    }

    @Override
    public void onResume() {
        super.onResume();
        shakeUtil.start();
        webView.onResume();//播放视频用的 继续播放
    }

    @Override
    public void onPause() {
        super.onPause();
        shakeUtil.stop();
        webView.onPause();//播放视频用的 暂停播放(不加的话即使也没关闭了也还是会听到声音)
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        HandlerUtil.removeRunable(runTimeOut);
    }

    private static List<UploadImage> upLoadList = new ArrayList<UploadImage>();
    private static UploadImage nowUpLoad = null;
    private static HttpHandler<String> nowHandler = null;

    /**
     *
     */
    private void startUpLoadImage(final String uploadUrl, final int sw, final int sh, final long size, final int sort) {

        if (upLoadList.size() <= 0) {
            return;
        } else {
            if (nowUpLoad == null) {
                nowUpLoad = upLoadList.get(0);
                try {
                    if (uploadUrl.contains("SaveVehicleProc")) {
                        nowUpLoad.filePath = BitmapUtil.smallBitmap(getActivity(), upLoadList.get(0).filePath, size, upLoadList.get(0).imageID);
                    } else {
                        nowUpLoad.filePath = BitmapUtil.smallBitmap(getActivity(), upLoadList.get(0).filePath, sw, sh, size, upLoadList.get(0).imageID);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                upLoadList.remove(0);
                DownLoadService downLoadService = getAppActivity().getDownLoadService();
                if (downLoadService != null) {

                    getAppActivity().setUploadLoadReceiverHandle(new IUpLoadListener() {
                        @Override
                        public void UploadStart(Context context, Intent intent, String url, String
                                tag) {
                        }

                        @Override
                        public void UploadLoading(Context context, Intent intent, String url, long
                                total, long current, String tag) {
                            JSONObject json = new JSONObject();
                            try {
                                json.put("tag", tag);
                                json.put("id", nowUpLoad.imageID);
                                json.put("total", total);
                                json.put("current", current);
                                float progress = (float) current / (float) total;
                                if ((float) (current / total) == 1) {
                                    progress = (float) 0.99;
                                }
                                json.put("progress", progress);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            executeJavascript("receiveDataFuntion(action, tag)"
                                    .replace("action", "'" + "fileProgress" + "'").replace("tag", "'" + json.toString() + "'"));
                        }

                        @Override
                        public void UploadFinish(Context context, Intent intent, String url, String
                                filePath, String webResult, String tag) {
                            try {
                                JSONObject json = new JSONObject(webResult);
                                json.put("tag", tag);
                                json.put("id", nowUpLoad.imageID);
                                executeJavascript("receiveDataFuntion(action, tag)"
                                        .replace("action", "'" + "fileDone" + "'").replace("tag", "'" + json.toString() + "'"));
                                FileUtil.deleteFile(new File(nowUpLoad.filePath));
                            } catch (IOException e) {
                                e.printStackTrace();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            nowUpLoad = null;
                            startUpLoadImage(uploadUrl, sw, sh, size, sort + 1);
                        }

                        @Override
                        public void UploadCancelled(Context context, Intent intent, String url,
                                                    String tag) {
                            JSONObject json = new JSONObject();
                            try {
                                json.put("tag", tag);
                                json.put("id", nowUpLoad.imageID);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            executeJavascript("receiveDataFuntion(action, tag)"
                                    .replace("action", "'" + "fileFail" + "'").replace("tag", "'" + json.toString() + "'"));
                            try {
                                FileUtil.deleteFile(new File(nowUpLoad.filePath));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            nowUpLoad = null;
                            startUpLoadImage(uploadUrl, sw, sh, size, sort + 1);
                        }

                        @Override
                        public void UploadError(Context context, Intent intent, String url, String
                                errorMsg, String tag) {
                            JSONObject json = new JSONObject();
                            try {
                                json.put("tag", tag);
                                json.put("id", nowUpLoad.imageID);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            executeJavascript("receiveDataFuntion(action, tag)"
                                    .replace("action", "'" + "fileFail" + "'").replace("tag", "'" + json.toString() + "'"));
                            try {
                                FileUtil.deleteFile(new File(nowUpLoad.filePath));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            nowUpLoad = null;
                            startUpLoadImage(uploadUrl, sw, sh, size, sort + 1);
                        }
                    });
                    String url = HttpUrlConstant.getWebSiteFullUrl(uploadUrl);
                    nowHandler = downLoadService.uploadHaveparamsAndRetHandler(nowUpLoad.TAG,
                            url, nowUpLoad.filePath, nowUpLoad.params, sort);
                }
            } else {
                LogUtils.e("正在上传中等待队列自然调用");
            }
        }
    }

    /**
     * 加工url 相对路径加http+网站,没有session的家__session__
     */
    String checkURL(String url) {
        if (Check.isEmpty(url)) {
            return null;
        }
        String fullURL = HttpUrlConstant.getWebSiteFullUrl(url);
        Map<String, String> parameters = HttpUrlConstant.getUrlParameters(fullURL);
        if (parameters == null || !parameters.containsKey("__session__")) {
            Map<String, String> map = new HashMap();
            map.put("__session__", AppApplication.getSession());
            return HttpUrlConstant.getWebSiteFullUrl(url, map);
        }
        return fullURL;
    }

    public void goBack() {
        if (webView != null) {
            webView.goBack();
        }
    }

    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        getAppActivity().openFileChooser(new IFileChooserListener() {
            @Override
            public void FileChooser(Context context, Intent intent, String fileFullName) {
                try {
                    if (fileFullName != null) {
                        if (fileFullName.indexOf("content://") >= 0) {
                            mUploadMessage.onReceiveValue(Uri.parse(fileFullName));
                        } else {
                            mUploadMessage.onReceiveValue(Uri.fromFile(new File(fileFullName)));
                        }
                    } else {
                        mUploadMessage.onReceiveValue(null);
                    }
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                }

                mUploadMessage = null;
            }
        });
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        mUploadMessageForAndroid5 = uploadMsg;
        getAppActivity().openFileChooser(new IFileChooserListener() {
            @Override
            public void FileChooser(Context context, Intent intent, String fileFullName) {

                try {
                    if (fileFullName != null) {
                        if (fileFullName.indexOf("content://") >= 0) {
                            mUploadMessageForAndroid5.onReceiveValue(new Uri[]{Uri.parse(fileFullName)});
                        } else {
                            mUploadMessageForAndroid5.onReceiveValue(new Uri[]{Uri.fromFile(new File(fileFullName))});
                        }
                    } else {
                        mUploadMessageForAndroid5.onReceiveValue(null);
                    }
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                }

                mUploadMessageForAndroid5 = null;

            }
        });

    }

    class PhoneObject {

        IReturnObject<String> onFinction = null;

        public void setOnFinction(IReturnObject<String> onFinction) {
            this.onFinction = onFinction;
        }

        /**
         * 主要用于android接受js方法的返回值
         *
         * @param result
         */
        @JavascriptInterface
        public void getResultContext(final String result) {
            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    if (onFinction != null) {
                        if (result.equalsIgnoreCase("undefined")) {
                            onFinction.returnResult(null);
                        } else {
                            onFinction.returnResult(result);
                        }

                    }
                }
            });
        }

    }

    public static final int ADDRES_GET = 3;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADDRES_GET) {
            if (resultCode == Activity.RESULT_OK) {
                data.putExtra("", "");
                String locationFullName = data.getStringExtra("locationFullName");
                String name = data.getStringExtra("name");
                String gps_longitude = "" + data.getDoubleExtra("gps_longitude", 0.0);
                String gps_latitude = "" + data.getDoubleExtra("gps_latitude", 0.0);
                LogUtils.e(""
                        + "locationFullName:" + locationFullName + "\n"
                        + "name:" + name + "\n"
                        + "gps_longitude:" + gps_longitude + "\n"
                        + "gps_latitude:" + gps_latitude + "\n"
                );
                executeJavascript("getMapLocationInfo(locationFullName, name, gps_longitude, gps_latitude)"
                        .replace("locationFullName", "'" + locationFullName + "'")
                        .replace("name", "'" + name + "'")
                        .replace("gps_longitude", gps_longitude)
                        .replace("gps_latitude", gps_latitude));
            }
        }
    }
}
